package com.dhz.common.solr.server;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.LBHttpSolrClient;
import org.springframework.beans.factory.DisposableBean;

/**
 * 提供solrj的访问入口的基本实现
 *
 * @author Fyduan
 */
public abstract class SolrClientFactoryBase implements SolrClientFactory, DisposableBean {

    private SolrClient solrClient;

    public SolrClientFactoryBase() {}

    SolrClientFactoryBase(SolrClient solrClient) {
        this.solrClient = solrClient;
    }

    /**
     * 判断是否是{@link HttpSolrClient}类型
     * @param solrClient {@link SolrClient}
     * @return 判断结果
     */
    protected final boolean isHttpSolrClient(SolrClient solrClient) {
        return solrClient instanceof HttpSolrClient;
    }

    @Override
    public SolrClient getSolrClient() {
        return this.solrClient;
    }

    public void setSolrClient(SolrClient solrClient) {
        this.solrClient = solrClient;
    }

    @Override
    public void destroy() throws Exception {
        destroy(this.solrClient);
    }

    /**
     * 销毁链接client方法
     * @param solrClient {@link SolrClient}
     * @throws Exception 抛出异常
     */
    protected void destroy(SolrClient solrClient) throws Exception {
        if (solrClient instanceof  HttpSolrClient) {
            ((HttpSolrClient) solrClient).close();
        } else if (solrClient instanceof LBHttpSolrClient) {
            ((LBHttpSolrClient) solrClient).close();
        } else {
            throw new Exception("不支持的Solr版本");
        }
    }
}
